<?php
/**
 * Created by PhpStorm.
 * User: xi
 * Date: 2020-04-21
 * Time: 23:28
 */

namespace app\api\service;

use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\Litestoreordergoods;
use app\admin\model\Order;
use app\admin\model\Profitorderundo;
use app\admin\model\Profitvip;
use app\admin\model\Userank;
use app\admin\model\Usercountprofit;
use app\admin\model\Userelation;
use app\admin\model\Userprofit;
use app\admin\model\Userreferprofit;
use app\admin\model\Userrelation;
use app\admin\model\Usertrade;
use app\common\model\User;
use think\Db;
use think\Exception;

class Orderservice
{


    //单品购买计算 不支持购物车 多个商品购买计算
    public function cacOrderAward($order)
    {

        if ($order['isdo'] == 1) return;

        Db::startTrans();
        try {
            $orderModel = new Litestoreorder();
            $orderModel->where('id', $order['id'])->update(['isdo' => 1]);
            $uid = $order['user_id'];
            $seller_id = $order['seller_id'];
            $userModel = new \app\admin\model\User();
            $sellUser = $userModel->where('id', $seller_id)->find();
            $buyRatio = $order['ratio'];
            $sellerRatio = 0;
            $litestoreOrderGoods = new Litestoreordergoods();
            $litestoreGoods = new Litestoregoods();
            $orderGoods = $litestoreOrderGoods->where('order_id', $order['id'])->find();
            $goods = $litestoreGoods->where('goods_id', $orderGoods['goods_id'])->find();
            if ($sellUser['group_id'] == 1) {
                $sellerRatio = 100;
            } else if ($sellUser['group_id'] == 2) {
                $sellerRatio = $goods['oneRatio'];
            } else if ($sellUser['group_id'] == 3) {
                $sellerRatio = $goods['twoRatio'];
            } else if ($sellUser['group_id'] == 4) {
                $sellerRatio = $goods['threeRatio'];
            }

            $uprofitOrderModel = new Profitorderundo();
            $ratio = $buyRatio - $sellerRatio;

            error_log("=====ratio======".$ratio);
            if ($ratio >= 0) {
                //零售差价
                $amount = $order['pay_price'] * $ratio / 100;
                if($amount >0){
                    $uprofitOrderModel->insert(['uid' => $seller_id, 'orderId' => $order['id'],
                        'amount' => $amount, 'ratio' => $ratio, 'createtime' => time(), 'type' => 'self', 'mark' => '零售差价']);
                }
                //开单费奖励
                $userRelationModel = new Userrelation();
                $userRelation = $userRelationModel->where('uid', $seller_id)->find();

                if ($userRelation) {
                    $relationship = $userRelation['relation'];
                    //计算等级分润
                    $sql = "select id,group_id from u_user where id in (" . $relationship . ")" . " ORDER BY FIND_IN_SET(id," . "'" . $relationship . "'" . ")";
                    $list = $userModel->query($sql);
                    $tempRank = 0;
                    $tempRate = 0;//发出汇总
                    if ($sellUser['group_id'] > 1) {
                        $tempRank = $sellUser['group_id'];
                    }

                    foreach ($list as $key => $val) {

                        if ($val['group_id'] - $tempRank > 0) {

                            $vRatio = 100;
                            if ($val['group_id'] == 2) {
                                $vRatio = $goods['oneRatio'];//90
                            } else if ($val['group_id'] == 3) {
                                $vRatio = $goods['twoRatio']; //80
                            } else if ($val['group_id'] == 4) {
                                $vRatio = $goods['threeRatio'];//70
                            }
                            $d = $sellerRatio - $tempRate - $vRatio;
                            error_log($d . "======d===vRatio==" . $vRatio . "====tempRate======" . $tempRate);
                            $tempRank = $val['group_id'];
                            $rankName = RankService::$nameConfig[$val['group_id']];
                            $tempRate += $d;
                            if ($d > 0) {
                                $a = $order['pay_price'] * $d / 100;
                                $uprofitOrderModel->insert(['uid' => $val['id'], 'orderId' => $order['id'],
                                    'amount' => $a, 'ratio' => $d, 'createtime' => time(), 'type' => 'team', 'mark' => $rankName . "开单奖励"]);
                            }

                        }

                    }


                    $rankService = new RankService();
                    $group3List = $rankService->getGroup3List($list);
                    if (count($group3List) > 0) {
                        $d = (2 / 100) / count($group3List);
                        $a = $order['pay_price'] * $d;
                        if ($a > 0) {
                            foreach ($group3List as $key => $val) {
                                $uprofitOrderModel->insert(['uid' => $val['id'], 'orderId' => $order['id'],
                                    'amount' => $a, 'ratio' => $d, 'createtime' => time(), 'type' => 'team', 'mark' => "U品代言人平级奖励"]);
                            }
                        }

                    }


                    $group4List = $rankService->getGroup4List($list);
                    if (count($group4List) > 0) {
                        $d = (2 / 100) / count($group4List);
                        $a = $order['pay_price'] * $d;
                        if ($a > 0) {
                            foreach ($group4List as $key => $val) {
                                $uprofitOrderModel->insert(['uid' => $val['id'], 'orderId' => $order['id'],
                                    'amount' => $a, 'ratio' => $d, 'createtime' => time(), 'type' => 'team', 'mark' => "U品合伙人平级奖励"]);
                            }
                        }

                    }


                }

            }

            Db::commit();
        } catch (Exception $e) {

            error_log("======error=======".$e->getMessage());
            Db::rollback();
            return false;
        }


    }


    /**
     * 推荐奖励
     */
    public function cacRefAward($order)
    {

        if ($order['isdo'] == 1) return;
        $uid = $order['user_id'];
        $orderModel = new Litestoreorder();
        $orderModel->where('id', $order['id'])->update(['isdo' => 1]);
        $userRelationModel = new Userrelation();
        $userRelation = $userRelationModel->where('uid', $uid)->find();

        if ($userRelation) {
            $relationship = $userRelation['relation'];
            $relArray = explode(",", $relationship);
            $userVipModel = new Profitvip();

            $userModel = new \app\admin\model\User();
            $profit = $userVipModel->where('orderId', $order['id'])->find();
            $ouid = $order['user_id'];
            if (!$profit) {
                if (count($relArray) >= 2) {
                    $ref_uid = $relArray[0];//直推
                    $two_ref_uid = $relArray[1];//间推

                    $amount = 120;
                    $twoAmount = 30;
                    $refUser = $userModel->field('id,group_id')->where('id', $ref_uid)->find();
                    if ($refUser['group_id'] > 1) {
                        $userVipModel->insert(['createtime' => time(), 'uid' => $ref_uid, 'amount' => $amount, "orderId" => $order['id'], "type" => 1, 'ouid' => $ouid, 'mark' => '直推奖励']);
                    }
                    $tworefUser = $userModel->field('id,group_id')->where('id', $two_ref_uid)->find();
                    if ($tworefUser['group_id'] > 1) {
                        $userVipModel->insert(['createtime' => time(), 'uid' => $two_ref_uid, 'amount' => $twoAmount, "orderId" => $order['id'], "type" => 2, 'ouid' => $ouid, 'mark' => '间推奖励']);
                    }

                    $userRelationModel->where(['uid' => $ref_uid])->setInc('t_one', 1);
                    $userRelationModel->where(['uid' => $ref_uid])->setInc('d_one', 1);


                } else {
                    $amount = 120;
                    $ref_uid = $relArray[0];//直推
                    $refUser = $userModel->field('id,group_id')->where('id', $ref_uid)->find();
                    if ($refUser['group_id'] > 1) {
                        $userVipModel->insert(['createtime' => time(), 'uid' => $ref_uid, 'amount' => $amount, "orderId" => $order['id'], "type" => 1, 'ouid' => $ouid, 'mark' => '直推奖励']);
                    }
                    $userRelationModel->where(['uid' => $ref_uid])->setInc('t_one', 1);
                    $userRelationModel->where(['uid' => $ref_uid])->setInc('d_one', 1);


                }

                //计算等级分润
                $sql = "select id,group_id from u_user where id in (" . $relationship . ")" . " ORDER BY FIND_IN_SET(id," . "'" . $relationship . "'" . ")";
                $list = $userModel->query($sql);

                $user = $userModel->field('id,group_id,username')->where('id', $uid)->find();
                $tempRank = 0;
                $tempRate = 0;//发出汇总

                if ($user['group_id'] > 1) {
                    $tempRank = $user['group_id'];
                    $tempRate = RankService::$vipConfig[$user['group_id']];
                }

                foreach ($list as $key => $val) {

                    if ($val['group_id'] - $tempRank > 0) {
                        $d = RankService::$vipConfig[$val['group_id']] - $tempRate;
                        $tempRank = $val['group_id'];
                        $rankName = RankService::$nameConfig[$val['group_id']];
                        $tempRate += $d;
                        if ($d > 0) {
                            $userVipModel->insert(['createtime' => time(), 'uid' => $val['id'], 'amount' => $d, "orderId" => $order['id'], "type" => 3, 'ouid' => $ouid, 'mark' => $rankName . '奖励']);
                        }
                    }

                }

                //计算代言人平级奖励
                $rankService = new RankService();
                $group3List = $rankService->getGroup3List($list);
                if (count($group3List) > 0) {
                    $amount = 6 / count($group3List);
                    foreach ($group3List as $key => $val) {
                        $userVipModel->insert(['createtime' => time(), 'uid' => $val['id'], 'amount' => $amount, "orderId" => $order['id'], "type" => 3, 'ouid' => $ouid, 'mark' => "U品代言人平级" . '奖励']);
                    }
                }
                error_log("====list====" . json_encode($list));
                $group4List = $rankService->getGroup4List($list);
                error_log("====group4List====" . json_encode($group4List));

                if (count($group4List) > 0) {
                    $amount = 6 / count($group4List);
                    foreach ($group4List as $key => $val) {
                        $userVipModel->insert(['createtime' => time(), 'uid' => $val['id'], 'amount' => $amount, "orderId" => $order['id'], "type" => 3, 'ouid' => $ouid, 'mark' => "U品合伙人平级" . '奖励']);
                    }

                }

            }

        }


    }
}